/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sys.screen;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.joda.time.DateTime;
import sys.bean.CaixaBean;
import sys.bean.PedidoBean;
import sys.dao.CaixaDao;
import sys.utils.Mensagens;
import sys.utils.Utils;

/**
 *
 * @author Administrador
 */
public class UIAnalisaCaixa extends javax.swing.JDialog {

    SimpleDateFormat formDataSpacTabela = new SimpleDateFormat("yyMMdd");
    SimpleDateFormat formDataSpac = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat formDataBr = new SimpleDateFormat("dd/MM/yyyy");
    NumberFormat formatoMoeda = NumberFormat.getCurrencyInstance();
    private List<CaixaBean> listaUsuarios;
    private final List<CaixaBean> listaCaixaDAnterior = new ArrayList<>();
    private final List<CaixaBean> listaCaixaDAtual = new ArrayList<>();
    DateTime contDataInicial;
    DateTime contDataFinal;

    public UIAnalisaCaixa(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        UIManager.put("Table.alternateRowColor", new java.awt.Color(230, 255, 255));
        setLocationRelativeTo(null);
        Utils.escClose(this);
        dataInicial.setDate(new Date());
        dataFinal.setDate(new Date());
        atualizaCombo();
        Utils.maximizarDialog(this);
    }

    /*
     atualizando combo com usuários do caixa
     */
    private void atualizaCombo() {
        try {
            cbUsuario.removeAllItems();
            listaUsuarios = CaixaDao.listaUsuarios(formDataSpacTabela.format(dataInicial.getDate()));

            for (CaixaBean caixa : listaUsuarios) {
                cbUsuario.addItem(caixa.getUsuario().getCodigo() + " - " + caixa.getUsuario().getNome() + " (" + caixa.getTerminal() + ")");
            }
        } catch (IOException | SQLException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }
    }

    /*
     Preenchendo objeto caixa
     */
    private void preencheObjDiaAnterior(String tabela) {
        CaixaBean caixa = null;
        try {
            caixa = CaixaDao.caixaDiaAnterior(listaUsuarios.get(cbUsuario.getSelectedIndex()).getUsuario().getCodigo(), tabela);
            caixa.getData();
            caixa.getSaldo1();
            caixa.getUsuario().getNome();

        } catch (SQLException | IOException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }
        listaCaixaDAnterior.add(caixa);
    }

    private void preencheObjDiaAtual(String tabela) {
        CaixaBean caixa = null;
        try {
            caixa = CaixaDao.caixaDiaAtual(listaUsuarios.get(cbUsuario.getSelectedIndex()).getUsuario().getCodigo(), tabela);
            caixa.getSaldo2();

        } catch (SQLException | IOException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }
        listaCaixaDAtual.add(caixa);
    }

    public void preencheListas() {

        listaCaixaDAnterior.clear();
        listaCaixaDAtual.clear();

        try {
            List<PedidoBean> diasTrabalhados = Utils.listaDiasTrabalhados(formDataSpac.format(dataInicial.getDate()), formDataSpac.format(dataFinal.getDate()));
            int size = diasTrabalhados.size();
            for (int i = 0; i < size; i++) {
                if (i == 0) {
                    preencheObjDiaAnterior(diasTrabalhados.get(i).getData().substring(2));
                } else {
                    preencheObjDiaAnterior(diasTrabalhados.get(i).getData().substring(2));
                    preencheObjDiaAtual(diasTrabalhados.get(i).getData().substring(2));
                }
            }

        } catch (SQLException | IOException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }
    }

    private void analisarCaixa() {

        DefaultTableModel modelo = (DefaultTableModel) tabelaAnalise.getModel();
        modelo.setNumRows(0);

        preencheListas();

        int size = listaCaixaDAtual.size();

        for (int i = 0; i < size; i++) {
            modelo.addRow(new Object[]{
                listaCaixaDAnterior.get(i).getData(), listaCaixaDAnterior.get(i).getUsuario().getNome(), formatoMoeda.format(listaCaixaDAnterior.get(i).getSaldo1()),
                formatoMoeda.format(listaCaixaDAtual.get(i).getSaldo2()), formatoMoeda.format(listaCaixaDAtual.get(i).getSaldo2() - listaCaixaDAnterior.get(i).getSaldo1())

            });
        }
        tabelaAnalise.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                String ref = table.getValueAt(row, 4).toString();

                if (Double.parseDouble(Utils.numParaCalculos(ref)) <= - 10 || Double.parseDouble(Utils.numParaCalculos(ref)) > 10) {
                    setForeground(Color.red);
                } else {
                    setForeground(Color.blue);
                }
                return this;
            }
        });

    }

    public String dataTabela() {
        String data = "";
        try {
            Date dataTabela = Utils.stringToDate(tabelaAnalise.getValueAt(tabelaAnalise.getSelectedRow(), 0).toString());

            data = formDataSpacTabela.format(Utils.addDias(dataTabela, 1));

        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            if (jTabbedPane1.getSelectedIndex() == 1) {
                Mensagens.msgAtencao("selecione a data do caixa!");
            }

        }
        return data;
    }

    private void analisaResumo() {

        DefaultTableModel modelo = (DefaultTableModel) tabelaResumo.getModel();
        modelo.setNumRows(0);

        try {
            for (CaixaBean caixa : CaixaDao.listaMovimentaxao(dataTabela(), listaUsuarios.get(cbUsuario.getSelectedIndex()).getUsuario().getCodigo())) {
                modelo.addRow(new Object[]{
                    tabelaAnalise.getValueAt(tabelaAnalise.getSelectedRow(), 0), caixa.getTransacao(), caixa.getHora(), caixa.getUsuario().getNome(), caixa.getMoeda(), formatoMoeda.format(caixa.getSaldo1()), caixa.getObs()
                });
            }
        } catch (com.extendedsystems.jdbc.advantage.ADSException e) {
            //

        } catch (SQLException | IOException ex) {
            Mensagens.msgErro("erro\n" + ex.getMessage());
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jpDados = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        dataInicial = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/#####", '_');
        dataFinal = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/#####", '_');
        cbUsuario = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaAnalise = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaResumo = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        btnSalvar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ANALISE ABERTURA/FECHAMENTO DE CAIXA");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jpDados.setBackground(new java.awt.Color(255, 255, 255));
        jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "SELECIONE DADOS:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 0, 10))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel2.setText("DATA INICIAL:");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel3.setText("DATA FINAL:");

        dataInicial.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        dataFinal.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        cbUsuario.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel4.setText("SELECIONE USUÁRIO:");

        javax.swing.GroupLayout jpDadosLayout = new javax.swing.GroupLayout(jpDados);
        jpDados.setLayout(jpDadosLayout);
        jpDadosLayout.setHorizontalGroup(
            jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(dataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(dataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(cbUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jpDadosLayout.setVerticalGroup(
            jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDadosLayout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cbUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jpDadosLayout.createSequentialGroup()
                        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addGap(1, 1, 1)
                        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(dataFinal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N

        tabelaAnalise.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tabelaAnalise.setForeground(new java.awt.Color(51, 102, 255));
        tabelaAnalise.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DATA FECH. CAIXA", "CAIXA RESPONSÁVEL", "VALOR FECHAMENTO", "ABER. DIA SEGUINTE", "DIFERENÇA"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaAnalise.setGridColor(new java.awt.Color(204, 204, 204));
        tabelaAnalise.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaAnaliseMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaAnalise);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 863, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );

        jTabbedPane1.addTab("ANALISAR CAIXA", jPanel2);

        tabelaResumo.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tabelaResumo.setForeground(new java.awt.Color(51, 102, 255));
        tabelaResumo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DATA", "TRANSACAO", "HORA", "CAIXA", "MOEDA", "VALOR", "OBSERVAÇÃO:"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaResumo.setGridColor(new java.awt.Color(204, 204, 204));
        jScrollPane2.setViewportView(tabelaResumo);
        if (tabelaResumo.getColumnModel().getColumnCount() > 0) {
            tabelaResumo.getColumnModel().getColumn(6).setPreferredWidth(250);
        }

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 863, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("RESUMO DO CAIXA", jPanel3);

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));

        btnSalvar.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/find-2.png"))); // NOI18N
        btnSalvar.setText("GERAR");
        btnSalvar.setPreferredSize(new java.awt.Dimension(120, 30));
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        jPanel4.add(btnSalvar);

        btnSair.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/sair.png"))); // NOI18N
        btnSair.setText("SAIR");
        btnSair.setPreferredSize(new java.awt.Dimension(120, 30));
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });
        jPanel4.add(btnSair);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpDados, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaAnaliseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaAnaliseMouseClicked

        if ((evt.getModifiers() & java.awt.event.MouseEvent.BUTTON3_MASK) != 0) {
            JPopupMenu menu = new JPopupMenu();
            JMenuItem item = new JMenuItem("ANALISAR RESUMO");
            item.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/edit.png")));
            menu.add(item);
            item.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    jTabbedPane1.setSelectedIndex(1);
                    analisaResumo();
                }
            });
            menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }

        analisaResumo();
    }//GEN-LAST:event_tabelaAnaliseMouseClicked

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed

        final BarraProgresso pb = new BarraProgresso(this);
        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                pb.gerarJanela();
                pb.lbDescricao.setText("ANALISANDO CAIXA, APENAS AGUARDE...");
                analisarCaixa();
                return null;
            }

            protected void done() {
                pb.fechar();
            }
        };
        worker.execute();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbUsuario;
    private com.toedter.calendar.JDateChooser dataFinal;
    private com.toedter.calendar.JDateChooser dataInicial;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel jpDados;
    private javax.swing.JTable tabelaAnalise;
    private javax.swing.JTable tabelaResumo;
    // End of variables declaration//GEN-END:variables
}
